package com.atguigu.gulimall.product.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author centurion
 * @description: spring-cache配置
 * @date 2025/2/19
 */
// CacheProperties.class中@ConfigurationProperties读取配置文件中的配置（spring.cache）实例化CacheProperties
// @EnableConfigurationProperties将CacheProperties注册到容器中
@EnableConfigurationProperties(CacheProperties.class)
@EnableCaching // 开启spring-cache 缓存
@Configuration
public class MyCacheConfig {

    //set注入
    // @Autowired
    // private CacheProperties cacheProperties;

    /**
     * 自定义配置了RedisCacheConfiguration，配置文件中的配置不会加载，在这里要手动指定
     * 参考 spring-boor-autoconfiure-2.2.6.RELEASE.jar中 RedisCacheConfiguration.createConfiguration的写法
     * @param cacheProperties
     * @return
     */
    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {//参数注入
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        //缓存的value使用json序列化
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        //过期时间
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }

        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }

        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }

        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }

        return config;
    }
}
